
<template>
    <van-nav-bar :title="route.meta.title" left-arrow @click-left="router.back()" fixed placeholder />
    <div v-if="!isLogin">
        <van-empty description="未登录" />
        <div class="loginBtn">
            <van-button type="primary" @click="router.push('/login')">去登陆</van-button>
        </div>
    </div>
    <div v-if="isLogin">
        <van-list v-if="cartStore.data?.length > 0" finished-text="没有更多了" offset @load="onLoad">
            <van-checkbox-group v-model="checkList" ref="checkboxGroup">
                <van-swipe-cell class="goods_item" v-for="item in cartStore.data" :key="item.id">
                    <van-checkbox :name="item.goods_info.id" class="selected"></van-checkbox>
                    <van-card :num="item.count" :price="(item.goods_info.price * item.count).toFixed(2)"
                        :desc="item.goods_info.detail_info" :title="item.goods_info.name" class="goods-card"
                        :thumb="item.goods_info.pic_url">
                        <template #tags>
                            <van-tag plain type="primary">{{ item.goods_info.tags }}</van-tag>
                        </template>
                        <template #footer>
                            <van-stepper v-model="item.count" @click="changeCount(item.goods_id, item.count, item.id
                            )" />
                        </template>
                    </van-card>
                    <template #right>
                        <van-button square text="删除" type="danger" class="delete-button" @click="deleteGood(item.id)" />
                    </template>
                </van-swipe-cell>
            </van-checkbox-group>
            <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit" v-if="isLogin" class="subBtn">
                <van-checkbox v-model="isSelectAll" @change="changeAll">全选</van-checkbox>
            </van-submit-bar>
        </van-list>
        <div v-else class="unLogin">
            <van-icon name="smile-o" size="50px" />
            <p>购物车空空空如也</p>
            <van-button type="primary" to="/home">去首页</van-button>
        </div>
    </div>
</template>
    
<script setup>
import { useRoute, useRouter } from 'vue-router'
import { getToken } from '@/utils/token.js'
import { useCartStore } from '@/stores/cart.js'
import { useAddressStore } from '@/stores/address.js'
import { ref, computed, watch } from 'vue'
import { deleteCart, updateCart } from '@/api/cart.js'
const cartStore = useCartStore();
const addressStore = useAddressStore()
const route = useRoute()
const router = useRouter()
//复选框组的实例
const checkboxGroup = ref(null);
//登录状态
let isLogin = ref(false);
//全选状态
let isSelectAll = ref(false)
//选中商品的列表
let checkList = ref([])
if (getToken()) {
    isLogin.value = true;
}

let onSubmit = () => {
    if (checkList.value.length != 0) {
        //筛选出选中的商品
        let res = cartStore.data.filter(item => checkList.value.includes(item.id))
        //过滤掉不需要的数据，并做简单处理
        let goodsList = res.map((item) => {
            return {
                count: item.count,
                goodsInfo: item.goods_info,
            };
        });
        //查看是否有默认地址
        let index = addressStore.data.findIndex(item => {
            return item.isDefault == true
        })
        //如果没有默认地址或是从没添加过地址要去地址列表页面选择地址
        if (addressStore.data.length == 0 || index == -1) {
            router.push({
                name: 'address',
                query: {
                    goodsInfo:
                        btoa(encodeURI(JSON.stringify(goodsList)))
                }
            })
        } else {
            //有默认地址就直接使用默认地址
            router.push({
                name: 'createOrder',
                query: {
                    orderInfo:
                        btoa(encodeURI(JSON.stringify({
                            goods: goodsList,
                            adress: addressStore.data[index]
                        })))
                }
            })

        }
    }


}
//删除购物车中某个商品
let deleteGood = async (id) => {
    await deleteCart([id])
    cartStore.getCart()
}
//购物车商品数量的修改
let changeCount = async (goods_id, count, id) => {
    await updateCart({
        goods_id,
        count,
        id
    })
    cartStore.getCart()
}
let onLoad = () => {

}

//监听选中商品列表的变化，如果符合条件让全选为true
watch(() => checkList.value, () => {
    isSelectAll.value = cartStore.data.every(item => checkList.value.includes(item.goods_info.id))
})
//全选和反选
let changeAll = (e) => {
    if (e == true) {
        checkboxGroup.value.toggleAll(true);
    } else {
        if ((cartStore.data.every(item => checkList.value.includes(item.goods_info.id)))) {
            checkboxGroup.value.toggleAll();
        }
    }

}

let totalPrice = computed(() => {
    let TP = 0
    cartStore.data.forEach(item => {
        if (checkList.value.includes(item.goods_info.id)) {
            TP += item.count * item.goods_info.price
        }
    })
    return TP * 100
})
</script>
    
<style lang="scss" scoped>
.loginBtn {
    text-align: center;
}


.unLogin {
    margin-top: .5333rem;
    text-align: center;
}

.goods_item {
    position: relative;

    .selected {
        position: absolute;
        z-index: 2;
        left: .2133rem;
        top: 1.4667rem;
    }

    .goods-card {
        padding-left: .9333rem;
        background-color: #fff;
    }

    .delete-button {
        height: 100%;
    }
}

.subBtn {
    bottom: 1.3333rem;
}
</style>